package com.limuzi.util;

import org.apache.commons.collections4.MapUtils;
import org.apache.http.HttpEntity;

import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * @author: limuzi
 * @create: 2023-06-26
 * 请求工具类
 */
public class HttpRequestUtils {
    private static final String CHARSET = "UTF-8";
    public static RequestConfig requestConfig = RequestConfig.custom()
            // 设置等待数据超时时间
            .setSocketTimeout(30000)
            // 设置链接超时时间
            .setConnectTimeout(30000)
            // 设置等待超时
            .setConnectionRequestTimeout(30000)
            .build();
    public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
        if(httpResponse != null){
            httpResponse.close();
        }
        if(httpClient != null){
            httpClient.close();
        }
    }
    public static String httpGet(String url, Map<String,String> header) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        if(!MapUtils.isEmpty(header)){
            header.forEach(httpGet::addHeader);
        }
        CloseableHttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity,CHARSET);
        httpGet.releaseConnection();
        release(response,httpClient);
        return result;
    }
    public static String httpGet(String url) throws IOException {
        return httpGet(url, null);
    }

    public static String httpPostJson(String url,String json,Map<String,String> header) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders= new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        for (Map.Entry<String,String> entry : header.entrySet()){
            httpHeaders.add(entry.getKey(),entry.getValue());
        }
        org.springframework.http.HttpEntity<String> request = new org.springframework.http.HttpEntity<>(json,httpHeaders);
        ResponseEntity<String> response = restTemplate.postForEntity(url,request, String.class);
        return response.getBody();
    }

    public static String httpPost(String url,Map<String,Object> params){
        return send(RequestBuilder.post(url),params);
    }

    private static String send(RequestBuilder requestBuilder,Map<String,Object>params){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        requestBuilder.setCharset(Charset.forName(CHARSET));
        String responseText = "";
        if(params != null){
            for (Map.Entry<String,Object> param : params.entrySet()){
                requestBuilder.addParameter(param.getKey(),param.getValue().toString());
            }

            CloseableHttpResponse response = null;
            try {
                response = httpClient.execute(requestBuilder.build());
                if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                    HttpEntity entity = response.getEntity();
                    if(entity != null){
                        responseText = EntityUtils.toString(entity,CHARSET);
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException("Http请求出现异常:"+ e);
            }finally {
                try {
                    response.close();
                } catch (Exception e) {
                    throw new RuntimeException("Http请求关闭出现异常:"+ e);
                }
            }
        }
        return responseText;
    }
}
